#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};
const static int defaultfd = -1;
using func_t = std::function<std::string(const std::string&, bool &ok)>;

class Udpserver
{
    public:
    Udpserver(uint16_t port, func_t func) : _sockfd(defaultfd), _port(port), _running(false), _func(func)
    {
    }
    void Initserver()
    {
        //1 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);

        //2 填充网络传输结构信息

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; 


        //3 绑定端口号
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");

    }

    void Start()
    {
        _running = true;
        while (true)
        {
            char request[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(sockaddr_in);

            ssize_t n = recvfrom(_sockfd,request,sizeof(request)-1,0,(struct sockaddr*)&peer,&len);
            if (n > 0)
            {
                request[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG,"get message from [%s:%d]:%s\n",addr.Ip().c_str(),addr.Prot(),request);
                bool ok;
                std::string response = _func(request, ok); // 将请求，回调出去，在外部进行数据处理
                // (void)ok;

                // 2. 将server收到的数据，发回给对方
                sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
        _running = false;
        
    }
    ~Udpserver()
    {}
    private:
    int _sockfd;
    uint16_t _port;
    bool _running;
    func_t _func;
};